//
//  FQGetValidateCodeHelper.m
//  JGRider
//
//  Created by 单启志 on 2018/3/8.
//  Copyright © 2018年 ffq. All rights reserved.
//

#import "FQGetValidateCodeHelper.h"
#import "JGValidateCodeApi.h"
@interface FQGetValidateCodeHelper()<YTKChainRequestDelegate>
@property(nonatomic,copy)void(^success)(NSString*);
@property(nonatomic,copy)void(^faile)(void);

@property(nonatomic,strong)MBProgressHUD *hud;
//系统返回的验证码
@property(nonatomic,copy)NSString *realValidateCode;

@property(nonatomic,strong)FQCountDownButton *btn;

@end

@implementation FQGetValidateCodeHelper

+(instancetype)share{
    static dispatch_once_t onceToken;
    static FQGetValidateCodeHelper *helper;
    dispatch_once(&onceToken, ^{
        helper=[[FQGetValidateCodeHelper alloc]init];
    });
    return helper;
}

-(void)getValidateCodeWithMobile:(NSString*)mobile view:(UIView*)view button:(FQCountDownButton*)btn sucess:(void(^)(NSString*code))success faile:(void(^)(void))faile{

    if (FQIsEmpty(mobile)) {
        [MBProgressHUD showError:@"请先输入手机号！" ToView:view];
        return;
    }
    _hud=[MBProgressHUD showMessage:@"获取中..." ToView:view];
    FQGetSignApi *signApi=[[FQGetSignApi alloc]initWithParams:[NSDictionary dictionaryWithObject:mobile forKey:@"mobile"]];
    FQChainRequest *chainReq=[[FQChainRequest alloc]init];
    [chainReq addRequest:signApi callback:^(YTKChainRequest * _Nonnull chainRequest, YTKBaseRequest * _Nonnull baseRequest) {
        FQGetSignApi *req=(FQGetSignApi*)baseRequest;
        JGValidateCodeApi *api=[[JGValidateCodeApi alloc]initWithSi:[req si] Pa:[req pa]];
        [chainRequest addRequest:api callback:nil];
    }];
    chainReq.delegate=self;
    [chainReq start];

    self.btn=btn;
    self.success=success;
    self.faile=faile;
}


#pragma mark api delegate
-(void)chainRequestFinished:(YTKChainRequest *)chainRequest{
    
    [_hud setHidden:YES];
    JGValidateCodeApi *api=(JGValidateCodeApi*)chainRequest.requestArray[1];
    _hud.label.text=@"获取成功";
    [_hud hideAnimated:YES afterDelay:0.5];
    NSString *validateCode=[api validateCode];
    _realValidateCode=validateCode;
    if (self.success) {
        [_btn clickNormalChange];
        self.success(validateCode);
    }
    NSLog(@"validateCode=%@",validateCode);
}

-(void)chainRequestFailed:(YTKChainRequest *)chainRequest failedBaseRequest:(YTKBaseRequest *)request{
    NSString *msg=request.responseJSONObject[@"data"][@"msg"];
    if (FQIsEmpty(msg)) {
        msg=request.responseJSONObject[@"data"][@"message"];
    }
    _hud.label.text=FQIsEmpty(msg)?@"网络连接失败":msg;
    [_hud hideAnimated:YES afterDelay:0.5];
    if (self.faile) {
        self.faile();
    }
    NSLog(@"%@",request.responseJSONObject);
    JGLog(@"%@",request.responseString);
}
@end
